package com.huiyun.project.im.common.auth;

import com.huiyun.project.common.core.util.SpringUtils;
import com.huiyun.project.common.core.util.WebUtils;
import org.wf.jwtp.provider.Token;
import org.wf.jwtp.util.SubjectUtil;

/**
 * @FileName: SecurityUtils
 * @Description:
 * @Author linjie
 * @Date 2020/7/183:47 PM
 * @Version 4.0.0
 */
public class SecurityUtils extends SubjectUtil {


    /**
     * 获取token
     *
     * @return
     */
    public static Token getToken() {
        return SubjectUtil.getToken(WebUtils.getRequest());
    }

    /**
     * 获取登陆的用户信息
     *
     * @return
     */
    public static AppPrincipal getAppPrincipal() {
        return (AppPrincipal) getPrincipal(SubjectUtil.getToken(WebUtils.getRequest()));
    }


    /**
     * 获取登陆的用户信息
     *
     * @return
     */
    public static UserPrincipal getUserPrincipal() {
        return (UserPrincipal) getPrincipal(SubjectUtil.getToken(WebUtils.getRequest()));
    }


    public static UserPrincipal getUserPrincipal(Token token) {

        return (UserPrincipal) getPrincipal(token);
    }

    public static AppPrincipal getAppPrincipal(Token token) {

        return (AppPrincipal) getPrincipal(token);
    }


    public static UserPrincipal getUserPrincipal(String uid) {

        return (UserPrincipal) getPrincipal(uid);
    }

    public static AppPrincipal getAppPrincipal(String appId) {

        return (AppPrincipal) getPrincipal(appId);
    }


    /**
     * 获取登陆的用户信息
     *
     * @return
     */
    private static Principal getPrincipal(Token token) {
        PrincipalService principalService = SpringUtils.getBean(PrincipalService.class);
        Principal principal = null;
        if (principalService != null) {
            principal = principalService.findPrincipalByUid(token.getUserId());
            principal.setId(token.getUserId());
            principal.setTerminal(token.getTerminal());
            principal.setRoles(token.getRoles());
            principal.setPermissions(token.getPermissions());
        }
        return principal;
    }


    /**
     * 获取登陆的用户信息
     *
     * @return
     */
    private static Principal getPrincipal(String userId) {
        PrincipalService principalService = SubjectUtil.getBean(PrincipalService.class);
        Principal principal = null;
        if (principalService != null) {
            principal = principalService.findPrincipalByUid(userId);
        }
        return principal;
    }
}
